package com.tan.androidtest.activity;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import com.tan.androidtest.R;
import com.tan.androidtest.service.TestService;

/**
 * 测试AlarmManager实现定时任务
 * AlarmManager有唤醒Cpu的功能, 非常适合做定时任务
 * 比如实现心跳
 */
public class TestAlarmManagerActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_alarmmanager_layout);
        init();
    }


    /**
     * 初始化
     */
    private void init() {
        startService(new Intent(this, TestService.class));
        TextView tv_test = findViewById(R.id.tv_test);
        tv_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //startOneTask();
                startRepeatTask();
            }
        });
    }

    /**
     * 使用AlarmManager启动一次任务
     */
    private void startOneTask() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, TestService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pendingIntent);
    }

    /**
     * 重复任务
     */
    private void startRepeatTask() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, TestService.class);
        intent.setAction("com.android.test");
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 6000, pendingIntent);
    }

}
